Find the prime number


Posted by Christy on 2023-01-20

Write a function named isPrime and pass a parameter n, if n is prime return true, else return false

function isPrime(n) {
  if (n === 1) return false;
  for (let i = 2; i < n; i++) {
    if (n % i === 0) {
      return false;
    }
  }
  return true;
}

function isPrime(n) {
  if (n === 1) return false;
  for (let i = 2; i < Math.sqrt(n); i++) {
    if (n % i === 0) {
      return false;
    }
  }
  return true;
}

console.log(isPrime(1));
console.log(isPrime(5));
console.log(isPrime(37));









Related Posts

110 四中兩科一政資工所甄試分享

110 四中兩科一政資工所甄試分享

Leetcode 刷題 pattern - Breadth-First Search

Leetcode 刷題 pattern - Breadth-First Search

AI輔導室|軟體自動完成算式

AI輔導室|軟體自動完成算式


Comments